<template>
	<gracePage :customHeader="false">
		<view slot="gBody" class="grace-body">
			<form @submit="formSubmit" class="grace-form grace-margin-top">
				<view class="grace-form-item grace-border-b">
					<text class="grace-icons icon-scancode grace-form-icon grace-blue"></text>
					<text class="grace-form-label">订单编码</text>
					<view class="grace-form-body">
						<view class="grace-form-input">{{orderCode}}</view>
					</view>
				</view>			
				<view class="grace-form-item grace-border-b">
					<text class="grace-icons icon-set grace-form-icon grace-blue"></text>
					<text class="grace-form-label">订单名称</text>
					<view class="grace-form-body">
						<view class="grace-form-input">{{productionField3}}</view>
					</view>
				</view>
				<view class="grace-form-item grace-border-b">
					<text class="grace-icons icon-wallet grace-form-icon grace-blue"></text>
					<text class="grace-form-label">订单金额</text>
					<view class="grace-form-body">
						<view class="grace-form-input">{{parseFloat(productionField12)+parseFloat(productionField13)}}元</view>
					</view>
				</view>		
			<!-- 	<view class="grace-form-item grace-border-b">
					<text class="grace-icons icon-help1 grace-form-icon grace-blue"></text>
					<text class="grace-form-label">支付方式</text>
					<view class="grace-form-body">
						<radio-group name="danxuan"> -->
							<!-- </br> -->
							<!-- <label class="grace-check-item-v"><radio :checked='payTypeRadio1Checked' value="微信"></radio>微信</br></label> -->
<!-- 							</br>
							<label class="grace-check-item-v"><radio :checked='payTypeRadio2Checked' value="支付宝"></radio>支付宝</br></label>
							</br>
						</radio-group>
					</view>
				</view>		 -->	
				<view class="demo">
					<view>
						<button formType="submit" type="primary" class="grace-button  grace-bg-blue" :disabled="formSubmitEnable">支付</button>
					</view>
				</view>		
			</form>	
		</view>
	</gracePage>
</template>
<script>
import gracePage from "../../graceUI/components/gracePage.vue";
var _self;
export default {
    data() {
        return {
			token :"",
			id : "",
			object : "",
			userInfoData : "",
			orderCode : "",
			productionField1 : "",
			productionField3 : "",
			productionField11 : "",
			productionField12 : "",
			productionField13 : "",
			payTypeRadio1Checked : false,
			payTypeRadio2Checked : true,
			formSubmitEnable:false
        }
    },
	onLoad: async function (e){
		_self = this;
		_self.$myFunction.displayLog("onLoad事件e:"+JSON.stringify(e));
		_self.id = e.id;
		// _self.id = 4;
		_self.orderCode = 'YXWS'+( _self.$myFunction.nowTime("Y-m-d H:i:s")).replace(/\s*/g,"").replace(/[:]/g, "").replace(/[-]/g, "");
		//获取token，同步方法
		_self.token =  await _self.$myFunction.getToken();
		_self.token = _self.token.token;
		// 获取详情
		_self.getObjectDetail();
	},
    methods:{
		getObjectDetail: function(){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
					'id': _self.id
				};
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}		
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;					
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'productionDetail',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},					
				success: data => {
					uni.hideToast();
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));
					if (data.data.code == 200) {
						_self.object = data.data.data.productionDto;
						_self.productionField1 = _self.object.field1;
						_self.productionField3 = _self.object.field3;
						_self.productionField11 = _self.object.field11;
						_self.productionField12 = _self.object.field12;
						_self.productionField13 = _self.object.field13;

					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/order/add'
									});
								}
							});
						}else{
							uni.showToast({title: "发生错误，请重试",icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			});				
		},
		formSubmit: function(e) {			
			_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
			_self.$myFunction.displayLog("_self.userInfoData"+JSON.stringify(_self.userInfoData));
			if(!_self.userInfoData){
				//因此页面是主页面，页面显示完成之后才能进行是否登录判断，延时2秒解决未登录提示一闪而过现象
				uni.showToast({title: '您未登录',icon: 'none'});//默认显示1500毫秒
				setTimeout(function () {
					uni.redirectTo({
						url:"../loginReg/index"
					})	
				}, 1500);
			}else{	
				var userPhone = _self.userInfoData.field2;
				// 支付方式
				// var payType = e.detail.value.danxuan;
				// if(!payType){
				// 	uni.showToast({title: '请选择支付方式',icon: 'none'});//默认显示1500毫秒
				// 	return false;
				// }
				var payType = "微信";
				var params = {
					"field1":_self.orderCode,//订单编码
					"field2":_self.productionField1,//产品编码
					"field3":_self.productionField3,//产品名称
					"field4":"",//用户信息,支付成功后回调设置为openId
					"field5":"",//快递名称
					"field6":"",//快递单号
					"field7":'',//收货地址
					"field8":'',//收货姓名
					"field9":'',//收货手机
					"field10":"",//快递费用
					"field11":1,//订单数量
					"field12":_self.productionField12,//订单单价
					"field13":parseFloat(_self.productionField12)+parseFloat(_self.productionField13),//订单金额
					"field14":"",//优惠金额
					"field15":"creating",//订单状态
					"field16":payType,//支付方式
					"field17":'油箱卫士',//订单信息
					"field18":userPhone,//下单用户
					"field19":'',//订单备注
					"field20":'',//其它数据
					"status":1
				};
				var paramsData = {
					"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
				}
				//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
				_self.token = _self.$myFunction.appStorage('wuLuToken').token;
				uni.request({
					url: _self.$myFunction.appConfig().serverAddress + 'productionOrderCreate',
					data: paramsData,
					method: "POST",
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authentication': _self.token
					},
					success: data => {
						_self.$myFunction.displayLog("productionOrderCreate服务器返回数据：" + JSON.stringify(data));
						let toastTitle, toastIcon, resType;
						if (data.data.code == 200) {
							_self.$myFunction.displayLog("订单创建成功" );
							//支付
							// _self.pay("云上天空","订单", _self.orderCode,_self.productionField12,"www.jyhzn.top");
							// _self.$myWXPay.wxPay1("云上天空", "订单", _self.orderCode, _self.productionField12, "云上天空", "www.jyhzn.top" ,"www.jyhzn.top");
							// _self.aliPay("云上天空", "订单", _self.orderCode, _self.productionField12, "云上天空", "www.jyhzn.top" ,"www.jyhzn.top");
							// _self.remoteControl("0","1131");//测试
							// uni.reLaunch({
							// 	url: '/pages/object/index'
							// });		
											
							let payUrl = _self.$myFunction.appConfig().serverIp + 'wechat/miniPay';
							_self.formSubmitEnable = true;
							_self.wxPay(payUrl, "油箱卫士", "油箱卫士", _self.orderCode, parseFloat(_self.productionField12)+parseFloat(_self.productionField13), "ty.hnztgckj.com" ,"ty.hnztgckj.com");
						}else{
							//如果请求数据因token认证失败，则清空缓存token
							if(data.data.message.indexOf("接口访问未认证") != -1){
								uni.setStorage({
									key: 'wuLuToken',
									data: "",
									success: function () {	
										_self.$myFunction.displayLog("清空缓存token");
										//触发重新获取token
										_self.$myFunction.getToken();
										// 关闭所有页面，打开到应用内的某个页面。
										_self.$myFunction.displayLog("重加载当前页面");
										uni.reLaunch({
											url: '/pages/order/add'	
										});
									}
								});
							}else{
								_self.$myFunction.displayLog("productionOrderCreate失败："+JSON.stringify(data));
								uni.hideToast();
								uni.showToast({title: '连接失败...',icon: 'none'});
							}	
						};
					},
					fail: (data, code) => {
						uni.hideToast();
						uni.showToast({title: '连接失败...',icon: 'none'});
					}
				});	
			}
		},
		aliPay : function(body, attach, out_trade_no, total_fee, goods_tag, notify_url ,successUrl){
			var params = {
				'body' : body,
				'attach' : attach,
				'out_trade_no' : out_trade_no,
				'total_fee' : total_fee,
				'goods_tag' : goods_tag,
				'notify_url' : notify_url,
				//发送收货信息使用参数
				'orderExpressAddress' : "",
				'orderExpressReceiverName' : "",
				'orderExpressReceiverPhone' : "",
				'orderNum' : "",
				'orderPrice' : "",
				'orderAmount' : "",
				'openIdMerchant' : "",
				'paySuccessUrl' : successUrl
			};	
			uni.request({
				url: _self.$myFunction.appConfig().serverIp + 'ali/appPay',
				data: params,
				method : "POST",
				header : {'content-type':'application/x-www-form-urlencoded'},					
				success: data => {
					// console.log(data.data);return;
					if (data.statusCode == 200) {
						// let urlTemp ="https://openapi.alipay.com/gateway.do?" + data.data;
						let orderInfo = data.data;
						uni.requestPayment({
						    provider: 'alipay',
						    orderInfo: orderInfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
						    success: function (res) {
						        // console.log('success:' + JSON.stringify(res));
								// {"channel":{"id":"alipay","description":"支付宝","serviceReady":true},"signature":"cyDKWV1xwWK0eVPke3YdxJMqenB4QWz3r/HNtRBorg+PrnDjQ9xJbHONDA5DiwJNt+VFk0W5nlKidZ773owqsHMTBOadLKLA7JHautbBTKpXuG/X7OHL75PWVYGpUeYalDvH5KQLP298v6f6btKCfAUF8sBulij1rPGQODd8jNzHntHrBaKDGRt+J/wb803tHOXT7m7KoUdBVTofwyJ+g2wBC8WRItE3JbtBNsPWWu8jasMV4zI3LKxKeWedef1q0EB+TmZGDbjjAcMu+Eu5h1Sb27SibK6GI8mkRmwlHJ9dVYlZZ7JkbDa0eYQG/GEXfloUAUUuQOvE3Qk1SZAvMg==","tradeno":"2024100822001433541403157175","rawdata":"{\"resultStatus\":\"9000\",\"memo\":\"\",\"result\":\"{\\\"alipay_trade_app_pay_response\\\":{\\\"code\\\":\\\"10000\\\",\\\"msg\\\":\\\"Success\\\",\\\"app_id\\\":\\\"2021004183627222\\\",\\\"auth_app_id\\\":\\\"2021004183627222\\\",\\\"charset\\\":\\\"UTF-8\\\",\\\"timestamp\\\":\\\"2024-10-08 21:28:21\\\",\\\"out_trade_no\\\":\\\"YSTK20241008212807\\\",\\\"total_amount\\\":\\\"12.00\\\",\\\"trade_no\\\":\\\"2024100822001433541403157175\\\",\\\"seller_id\\\":\\\"2088141425364567\\\"},\\\"sign\\\":\\\"cyDKWV1xwWK0eVPke3YdxJMqenB4QWz3r\\/HNtRBorg+PrnDjQ9xJbHONDA5DiwJNt+VFk0W5nlKidZ773owqsHMTBOadLKLA7JHautbBTKpXuG\\/X7OHL75PWVYGpUeYalDvH5KQLP298v6f6btKCfAUF8sBulij1rPGQODd8jNzHntHrBaKDGRt+J\\/wb803tHOXT7m7KoUdBVTofwyJ+g2wBC8WRItE3JbtBNsPWWu8jasMV4zI3LKxKeWedef1q0EB+TmZGDbjjAcMu+Eu5h1Sb27SibK6GI8mkRmwlHJ9dVYlZZ7JkbDa0eYQG\\/GEXfloUAUUuQOvE3Qk1SZAvMg==\\\",\\\"sign_type\\\":\\\"RSA2\\\"}\"}","errMsg":"requestPayment:ok"} 
								uni.showToast({title: '支付成功',icon: 'none'});
								//支付成功后返回并刷新detail 课程购买标志
								uni.$emit('paySuccessRefresh', {
									msg: '支付成功页面object/detail刷新'
								});
								setTimeout(function () {
									uni.navigateBack();
								}, 1500);
							},
						    fail: function (err) {
						        // console.log('fail:' + JSON.stringify(err));
								uni.showToast({title: '支付失败，请联系客服',icon: 'none'});
						    }
						});

						
						
						
						
						// //统一下单
						// uni.request({
						// 	url: urlTemp,
						// 	method: 'GET',
						// 	// header: { 'content-type': 'application/x-www-form-urlencoded' },
						// 	success(res) {
						// 		console.log(res);return;
								
								
						// 		// 微信支付
						// 		uni.requestPayment({
						// 			timeStamp: res.data.timeStamp,
						// 			nonceStr: res.data.nonceStr,
						// 			package: res.data.package,
						// 			signType: res.data.signType,
						// 			paySign: res.data.paySign,
						// 			success: (res) => {
						// 				uni.showToast({
						// 					title: "支付成功",
						// 					duration: 2000						
						// 				})
						// 				setTimeout(function () {
						// 					uni.switchTab({
						// 						url: successUrl
						// 					});								
						// 				}, 2000)
						// 			},
						// 			fail: (res) => {
						// 				uni.showModal({
						// 					content: "支付失败: " + res.errMsg,
						// 					showCancel: false,
						// 				});
						// 			},
						// 			complete: () => {
						// 			// this.loading = false;
						// 			}
						// 		})			   
						// 	},
						// 	fail: (data, code) => {
						// 		uni.showToast({title: '连接失败...',icon: 'none'});
						// 	}
						// })	
											
					}else{
						uni.showToast({title: '服务器返回失败...',icon: 'none'});
						return false;								
					}
				},
				fail: (data, code) => {
					console.log(data);return;
					uni.showToast({title: '连接失败...',icon: 'none'});
					return false;		
				}					
			});
		},
		wxPay:function(payUrl,body,attach,orderCode,total,notify_url,paySuccessUrl){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					uni.hideToast();
					//根据code从服务器换取openid
					_self.formSubmitEnable = true;
					uni.request({
						url: _self.$myFunction.appConfig().serverIp +'wechat/getWxMiniOpenid/' + loginRes.code,
						method: "GET",
						success: data => {
							_self.$myFunction.displayLog("根据code从服务器换取openid返回数据：" + JSON.stringify(data));
							//根据code从服务器换取openid返回数据：{"data":{"code":200,"data":"{\"session_key\":\"zh+khf2302b6Rn9F4Yw0Yw==\",\"openid\":\"o35XE5Kq_fr_5KhzhJSnxOPEHWoY\"}"},"header":{"Vary":"Origin,Access-Control-Request-Method,Access-Control-Request-Headers","Content-Type":"application/json","Transfer-Encoding":"chunked","Date":"Tue, 08 Aug 2023 07:36:11 GMT","Keep-Alive":"timeout=60","Connection":"keep-alive"},"statusCode":200,"cookies":[],"errMsg":"request:ok"}
							if (data.data.code == 200) {
								//利用获取到的openid、session_key和上一步骤获的encryptedData、iv解密
								_self.openId = JSON.parse(data.data.data).openid;
								
								let params = {
									'openid':_self.openId,
									'description' : body,
									'attach' : attach,
									'outTradeNo' : orderCode,
									'total' : total,
									'goodsTag' : "",
									'notifyUrl' : notify_url,
									//发送收货信息使用参数
									'orderExpressAddress' : "",
									'orderExpressReceiverName' : "",
									'orderExpressReceiverPhone' : "",
									'orderNum' : "",
									'orderPrice' : "",
									'orderAmount' : "",
									'openIdMerchant' : "",
									'paySuccessUrl' : paySuccessUrl
								};
								var paramsData = {
									"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
								}
								// 统一下单
								uni.request({
								  url: payUrl, 
								  data: paramsData,
								  method: 'GET',
								  header: {
								  	'content-type': 'application/x-www-form-urlencoded'
								  },
								  success: function (res) {
									  uni.hideToast();
									  _self.$myFunction.displayLog("统一下单：" + JSON.stringify(res));
									// 微信支付
									uni.requestPayment({
										timeStamp: res.data.data.timeStamp,
										nonceStr: res.data.data.nonceStr,
										package: res.data.data.packageVal,
										signType: res.data.data.signType,
										paySign: res.data.data.paySign,
										success: (res) => {
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											});
											//清空购物车
											uni.$emit('orderListRefresh', {
												msg: '页面刷新'
											});
											setTimeout(function () {
												uni.redirectTo({
													url: '/pages/order/index'
												})							
											}, 1500)
										},
										fail: (res) => {
											_self.formSubmitEnable = false;
											uni.showModal({
												content: "支付失败",
												showCancel: false,
											});
										},
										complete: () => {
											// this.loading = false;
										}
									})	
								  },
									fail: (data, code) => {
										_self.formSubmitEnable = false;
										uni.showToast({title: '连接失败...',icon: 'none'});
									}
								})
							} else {
								_self.formSubmitEnable = false;
								uni.showToast({
									title: '服务器返回失败...',
									icon: 'none'
								});
							}
						},
						fail: (data, code) => {
							_self.formSubmitEnable = false;
							uni.showToast({
								title: '连接失败...',
								icon: 'none'
							});
						}
					});
				},
				fail: function(e) {
					uni.hideToast();
					_self.formSubmitEnable = false;
					uni.showToast({
						title: '微信授权登录失败',
						icon: 'none'
					});
				}
			});
		},
		/**
		 * 远程控制
		 * @param
		 */
		remoteControl:function(val,codeValue){
			_self.imei = _self.$myFunction.appStorage('imei');
			if( _self.$myFunction.isEmpty(_self.imei)){
				uni.showToast({title: '无设备',icon: 'none'});//默认显示1500毫秒
				setTimeout(function () {
					uni.navigateTo({
						url:"../hardware/bind"
					})	
				}, 1500);
			}else{
				var params = {
					"imei":_self.imei,
					"val":val,
					"oneNetCode":codeValue
				};
				//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
				_self.token = _self.$myFunction.appStorage('wuLuToken').token;
				uni.showToast({
					title: '请稍后',
					duration: 50000,
					icon: 'loading'
				});
				_self.buttonFunctionState = 1;
				uni.request({
					url:  _self.$myFunction.appConfig().serverAddress+'downloadCode',
					data: params, 
					method : "POST",
					header : {
						'content-type':'application/x-www-form-urlencoded',
						'Authentication':_self.token
					},	
					success: function (data) {
						uni.hideToast();
						_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));
						//{"code":200,"data":"success"}
						//{"code":500,"message":"下发失败"}
						if (data.data.code === 200) {
							// my_alert(".my_alert","操作成功！",false,"success");
							uni.showToast({title: '操作成功！',icon: 'success'});
						}else{
							// my_alert(".my_alert","下发失败",false,"warning");
							uni.showToast({title: '下发失败',icon: 'none'});
						}
						_self.buttonFunctionState=0;
					},
					complete:function (data) {
						_self.buttonFunctionState=0;
					},
					error:function (data) {
						uni.showToast({title: '请重试',icon: 'none'});
						_self.buttonFunctionState=0;
						// console.log(JSON.stringify(data));
						// {"readyState":4,"responseText":"{\"message\":\"接口访问未认证，请先进行认证\"}","responseJSON":{"message":"接口访问未认证，请先进行认证"},"status":401,"statusText":"error"}
						if(JSON.stringify(data).indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/hardware/index'
									});
								}
							});
						}
					},
					fail: (data, code) => {
						uni.hideToast();
						uni.showToast({title: '连接失败...',icon: 'none'});
					}
				})
			}
		}
    },
	components: {
		gracePage
	}
}
</script>
<style>
	.grace-form-icon{font-size:40rpx;}
	.grace-form-label{width:170rpx;font-size:medium;}
	.grace-form-input{font-size:40rpx;text-align:left;margin:20rpx;}
	/* 按钮 */
	.demo{display:flex; flex-wrap:nowrap; border-left:1px solid #F8F8F8;}
	.demo view{width:100%; text-align:center; margin:10rpx;}
	/* 列表支付方式选择 */
	.grace-check-item-v{width:100%; padding:55rpx 0;font-size:40rpx;}
</style>